/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.yangxu.hospital.system.modules.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangxu.hospital.common.config.RsaProperties;
import com.yangxu.hospital.common.exception.BadRequestException;
import com.yangxu.hospital.common.utils.PageResult;
import com.yangxu.hospital.common.utils.RsaUtils;
import com.yangxu.hospital.common.utils.SecurityUtils;
import com.yangxu.hospital.common.utils.enums.CodeEnum;
import com.yangxu.hospital.logging.annotation.Log;
import com.yangxu.hospital.system.modules.system.domain.Role;
import com.yangxu.hospital.system.modules.system.domain.SysPatient;
import com.yangxu.hospital.system.modules.system.domain.User;
import com.yangxu.hospital.system.modules.system.domain.dto.UserDto;
import com.yangxu.hospital.system.modules.system.domain.vo.UserPassVo;
import com.yangxu.hospital.system.modules.system.domain.vo.UserQueryCriteria;
import com.yangxu.hospital.system.modules.system.service.*;
import com.yangxu.hospital.tools.utils.BarcodeAndQRCodeGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final RoleService roleService;
    private final VerifyService verificationCodeService;
    private final SysPatientService sysPatientService;

    @ApiOperation("导出用户数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:list')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
        List<User> users = userService.queryAllNoIsDoctorUsers();
        userService.download(userService.queryAll(criteria), response);
        System.out.println(users);
    }
    @ApiOperation("查出所有未分配的医生")
    @GetMapping(value = "/getNoIsDoctorUsers")
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<List<User>> getNoIsDoctorUsers() {
        List<User> users = userService.queryAllNoIsDoctorUsers();
        return new ResponseEntity<>(users,HttpStatus.OK);
    }

    @ApiOperation("查询用户")
    @GetMapping
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<PageResult<User>> queryUser(UserQueryCriteria criteria, Page<Object> page){
        // 直接查询所有用户
        return new ResponseEntity<>(userService.queryAll(criteria,page),HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){
        checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
        for (Long id : ids) {
            Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(Role::getLevel).collect(Collectors.toList()));
            if (currentLevel > optLevel) {
                throw new BadRequestException("角色权限不足，不能删除：" + userService.findById(id).getUsername());
            }
        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("重置密码")
    @PutMapping(value = "/resetPwd")
    public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids) {
        String pwd = passwordEncoder.encode("123456");
        userService.resetPwd(ids, pwd);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }

    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateUserEmail(@PathVariable String code, @RequestBody User resources) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,resources.getPassword());
        User user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(password, user.getPassword())){
            throw new BadRequestException("密码错误");
        }
        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + resources.getEmail(), code);
        userService.updateEmail(user.getUsername(),resources.getEmail());
        return new ResponseEntity<>(HttpStatus.OK);
    }
    /**
     * 修改个人信息
     */
    @ApiOperation(value = "h5获取个人信息")
    @GetMapping("/getUserInfo")
    public ResponseEntity<Object> getUserInfo() throws Exception {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String currentUsername = SecurityUtils.getCurrentUsername();
        if (StringUtils.hasText(currentUsername)){
            userLambdaQueryWrapper.eq(User::getUsername, currentUsername);
        }
        User one = userService.getOne(userLambdaQueryWrapper);
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(one,userDto);
        // 生成条形码和二维码
        String barcodeBase64 = generateBarcodeBase64(one.getMedicalCard());
        String qrCodeBase64 = generateQRCodeBase64(one.getMedicalCard());
        userDto.setBarcodeBase64(barcodeBase64);
        userDto.setQrCodeBase64(qrCodeBase64);
        SysPatient byId = sysPatientService.getById(one.getId());
        userDto.setAllergies(byId.getAllergies());
        userDto.setEmergencyContact(byId.getEmergencyContact());
        return ResponseEntity.ok(userDto);
    }

    /**
     * 修改个人信息
     */
    @ApiOperation(value = "h5修改个人信息")
    @PostMapping("/updateUserInfo")
    public ResponseEntity<?> updateUserInfo(@RequestBody UserDto request) {
        String allergies = request.getAllergies();
        LambdaQueryWrapper<SysPatient> sysPatientLambdaQueryWrapper = new LambdaQueryWrapper<>();
        SysPatient sysPatient = new SysPatient();
        if(StringUtils.hasText(allergies)){
            sysPatientLambdaQueryWrapper.eq(SysPatient::getPatientId,request);
            sysPatient.setPatientId(request.getId());
            sysPatient.setAllergies(allergies);
        }
        if (StringUtils.hasText(request.getEmergencyContact())){
            sysPatient.setEmergencyContact(request.getEmergencyContact());
        }
        sysPatientService.updateById(sysPatient);
        return ResponseEntity.ok(userService.updateById(request));
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     * @param resources /
     */
    private void checkLevel(User resources) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(Role::getLevel).collect(Collectors.toList()));
        Integer optLevel = roleService.findByRoles(resources.getRoles());
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足");
        }
    }
    private String generateBarcodeBase64(Long medicalCard) throws Exception {
        return BarcodeAndQRCodeGenerator.generateBarcodeBase64(String.valueOf(medicalCard), 300, 80);
    }

    private String generateQRCodeBase64(Long medicalCard) throws Exception {
        return BarcodeAndQRCodeGenerator.generateQRCodeBase64(String.valueOf(medicalCard), 400, 400);
    }
}
